#!/bin/bash
usage()
{
cat << EOF
usage: $0 [-u <tarball-url>] [-f <tarball-file>]

This script creates a new Tomcat 6 debian package from the Tomcat tarball or by downloading
the tarball from a URL.

OPTIONS:
   -h      Show this message
   -u      The URL of the Tomcat6 tarball
   -f      The path to the Tomcat6 tarball file
EOF
}

# Parse the options
URL=
FILE=
while getopts "h:u:f:" OPTION; do
  case $OPTION in
    h)
      usage
      exit 0
      ;;
    u)
      URL=$OPTARG
      ;;
    f)
      if [ -f $OPTARG ]; then
        DIR=$(dirname $OPTARG)
        cd $DIR
        FILE="${PWD}/$(basename $OPTARG)"
        cd -
      else
        usage
        exit 1
      fi
      ;;
  esac
done

if [[ -z $URL && -z $FILE ]]; then
  usage
  exit 1
fi


BASEDIR=$PWD


# Make the target directory
if [ -d target ]; then
  echo "Deleting up old target directory"
  rm -rf target
fi
  
mkdir target
cd target


#
# Download the Tomcat tarball and use that to construct the packages
#

if [ ! -z $URL ]; then
  if ! curl $URL > tomcat.tar.gz; then
    echo "Unable to download tarball"
    exit 1
  fi

  FILE=tomcat.tar.gz
fi

if ! tar -xzf $FILE; then
  echo "Unable to extract tarball"
  exit 1
fi

# Figure out the version #
VERSION=
for f in $(ls); do
  if [ -d $f ]; then
    VERSION=${f##apache-tomcat-}
  fi
done



#
# Setup the tomca6 package layout
#

# Create the tomcat6 dir
mkdir -p tomcat6/usr/share/tomcat6/skel

# Copy the bin and conf dir to the tomcat6 locations
cp -r apache-tomcat-$VERSION/bin tomcat6/usr/share/tomcat6/skel
cp -r apache-tomcat-$VERSION/conf tomcat6/usr/share/tomcat6/skel

# Copy the scripts and such for our package so that they overwrite the file from the tarball
cp -r $BASEDIR/tomcat6/files/usr tomcat6
cp -r $BASEDIR/tomcat6/debian/DEBIAN tomcat6

# Clean up a bit
find tomcat6 -name '.svn' | xargs rm -r
find tomcat6 -name '*.bat' | xargs rm
find tomcat6 -name '*.exe' | xargs rm


#
# Create the tomcat6 deb package
#
fakeroot dpkg -b tomcat6



#
# Setup the libtomca6-java package layout
#

# Copy the scripts and such for our package
mkdir -p libtomcat6-java/usr/share/java
cp -r $BASEDIR/libtomcat6-java/debian/DEBIAN libtomcat6-java

# Copy the JAR files over and rename them all to include the version # of Tomcat6
cp apache-tomcat-$VERSION/lib/*.jar libtomcat6-java/usr/share/java
for f in $(ls libtomcat6-java/usr/share/java); do
  mv libtomcat6-java/usr/share/java/$f libtomcat6-java/usr/share/java/${f%%.jar}-$VERSION.jar
  pushd libtomcat6-java/usr/share/java > /dev/null
  ln -s ${f%%.jar}-$VERSION.jar $f
  popd > /dev/null
done


# Clean up a bit
find libtomcat6-java -name '.svn' | xargs rm -r


#
# Create the tomcat6 deb package
#
fakeroot dpkg -b libtomcat6-java

